package com.kyomonn.talkischeap;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity {

    private SharedPreferences sharedPref;
    private EditText etUserName, etPassword;
    private CheckBox cbRememberMe;
    private MySQLiteOpenHelper mySQLiteOpenHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        sharedPref = getSharedPreferences("user_data", Context.MODE_PRIVATE);

        // 绑定视图
        etUserName = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        cbRememberMe = findViewById(R.id.cb_remember_me);
        Button btnLogin = findViewById(R.id.btn_login);
        TextView tvRegisterLink = findViewById(R.id.tv_register_link);

         if (sharedPref.getBoolean("remember_me", false)) {
            etUserName.setText(sharedPref.getString("username", ""));
            etPassword.setText(sharedPref.getString("password", ""));
            cbRememberMe.setChecked(true);
        }

        // 登录点击事件
        btnLogin.setOnClickListener(v -> loginUser());

        // 注册链接跳转
        tvRegisterLink.setOnClickListener(v -> {
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            intent.putExtra("username", etUserName.getText().toString());
            intent.putExtra("password", etPassword.getText().toString());
            startActivityForResult(intent, 1);
        });
    }

    private void loginUser() {
        String username = etUserName.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "请输入用户名和密码", Toast.LENGTH_SHORT).show();
            return;
        }

        mySQLiteOpenHelper = new MySQLiteOpenHelper(this, "LocalStorage.db", null, 1);
        SQLiteDatabase db = mySQLiteOpenHelper.getWritableDatabase();
        String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
        Cursor cursor = db.rawQuery(sql, new String[]{username, password});
        SharedPreferences.Editor editor = sharedPref.edit();

        if (cursor.moveToFirst()) {
            // 登录成功
            Toast.makeText(this, "登录成功！欢迎 " + username, Toast.LENGTH_SHORT).show();

            editor.putBoolean("remember_me", cbRememberMe.isChecked());
            editor.putString("username", username);
            editor.putString("password", password);
            editor.putBoolean("is_login", true);
            editor.apply();
            sql = "SELECT email FROM users WHERE username = ?";
            cursor = db.rawQuery(sql, new String[]{username});
            if (cursor.moveToFirst()) {
                int emailIndex = cursor.getColumnIndex("email");
                if (emailIndex >= 0) {
                    editor.putString("email", cursor.getString(emailIndex));
                    editor.apply();
                } else {
                    Toast.makeText(this, "找不到邮箱", Toast.LENGTH_SHORT).show();
                }
            }

            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        } else {
            // 登录失败
            Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
        }
        cursor.close();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                assert data != null;
                String username = data.getStringExtra("username");
                String password = data.getStringExtra("password");
                etUserName.setText(username);
                etPassword.setText(password);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mySQLiteOpenHelper.close();
    }
}
